<?php

namespace app\api\lists\userreimbursement;

use app\api\lists\BaseApiDataLists;
use app\common\lists\ListsSearchInterface;
use app\common\model\reimbursement\ExpenseApplication;
use app\common\model\user\User;

class UserExpenseApplicationLists extends BaseApiDataLists implements ListsSearchInterface
{
    /**
     * @notes 搜索条件
     * @return \string[][]
     */
    public function setSearch(): array
    {
        return [
            '=' => ['current_status'],
            '%like%' => ['applicant_men', 'expense_type', 'desription'],
            'between' => ['amount']
        ];
    }

    /**
     * @notes 获取列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function lists(): array
    {

        // 添加用户ID过滤条件
        $userId = $this->request->userId;
        $applicantId = $this->request->get('applicant_id');
        if ($applicantId !== null && $applicantId !== '') {
            $this->searchWhere[] = ['applicant_id', '=', $applicantId];
        } else {
            $this->searchWhere[] = ['applicant_id', '=', $userId];
        }

        // 金额范围筛选
        $min = $this->request->get('min_amount');
        if ($min !== null && $min !== '') {
            $this->searchWhere[] = ['amount', '>=', $min];
        }
        $max = $this->request->get('max_amount');
        if ($max !== null && $max !== '') {
            $this->searchWhere[] = ['amount', '<=', $max];
        }

        $list = ExpenseApplication::with(['applicant', 'expenseType'])  // 关联申请人和费用类型
            ->where($this->searchWhere)
            ->field([
                'id', 
                'applicant_id', 
                'expense_type_id', 
                'amount', 
                'description', 
                'current_status',
                'create_time',
                'update_time'
            ])
            ->order(['id' => 'desc'])
            ->paginate([
                'page' => $this->pageNo,
                'list_rows' => $this->pageSize
            ])
            ->toArray();

        // 状态映射说明
        $statusMap = [
            0 => '待提交',
            1 => '待审批',
            2 => '已退回',
            3 => '已通过',
        ];

        $processedList = array_map(function ($item) use ($statusMap, $userId) {
            $item['status_desc'] = $statusMap[$item['current_status']] ?? '未知状态';
            $item['auto_approved'] = ($item['current_status'] == 3) ? '是' : '否';
            $item['is_self'] = ($item['applicant_id'] == $userId);
            // 添加申请人和费用类型信息
            $item['applicant_name'] = $item['applicant']['nickname'] ?? '';
            $item['expense_type_name'] = $item['expenseType']['name'] ?? '';
            // 移除关联数据
            unset($item['applicant'], $item['expenseType']);
            return $item;
        }, $list['data']);

        return [
            'count' => $list['total'],
            'lists' => $processedList,
            'page_no' => $list['current_page'],
            'page_size' => $list['per_page'],
            'extend' => []
        ];
    }

    /**
     * @notes 获取数量
     * @return int
     */
    public function count(): int
    {
        return ExpenseApplication::where($this->searchWhere)->count();
    }
}